const express = require("express");
const router = express.Router();
//导入数据库 sqlFn('sql',[],res=>{})
const sqlFn = require("./mysql");
// 引入图片模块
const multer = require("multer");
const fs = require("fs");
const jwt = require("jsonwebtoken");
const config = require("./secert");
const Mock = require("mockjs");
/**
 * 商品列表：获取分页 {total:'',arr:[{},{},{}],pagesize:8,}
 * 参数：page 页码
 */

router.get("/", (req, res) => {
    res.send("home 页面");
});

router.get("/projectList", (req, res) => {
    const page = req.query.page || 1;
    const sqlLen = "select * from project where id";
    sqlFn(sqlLen, null, (data) => {
        let len = data.length;
        const sql = "select * from project order by id desc limit 8 offset 0" + (page - 1) * 8;
        sqlFn(sql, null, (result) => {
            if (result.length > 0) {
                res.send({
                    status: 200,
                    data: result,
                    pageSize: 8,
                    total: len,
                });
            } else {
                res.send({
                    status: 500,
                    msg: "暂无数据",
                });
            }
        });
    });
});

/**
 * 商品查询接口 search
 * 参数：search
 */
router.get("/search", (req, res) => {
    let search = req.query.search;
    const sql =
        "select * from project where concat(`title`,`sellPoint`,`descs`) like '%" + search + "%'";
    sqlFn(sql, null, (result) => {
        if (result.length > 0) {
            res.send({
                status: 200,
                result,
            });
        } else {
            res.send({
                status: 500,
                msg: "暂无数据",
            });
        }
    });
});

/**
 * 类目选择
 * 接口说明：接口不同的参数cid 返回不同的类目数据 后台接受变量：id
 */
router.get("/backend/itemCategory/selectItemCategoryByParentId", (req, res) => {
    const id = req.query.id || 1;
    const sql = "select * from category where cid";
    let arr = [id];
    sqlFn(sql, arr, (result) => {
        if (result.length > 0) {
            res.send({
                status: 200,
                result,
            });
        } else {
            res.send({
                status: 500,
                msg: "暂无数据",
            });
        }
    });
});

/**
 * 类目结构数据获取
 */
router.get("/category/data", (req, res) => {
    let cid = req.query.cid;
    let sql = "select * from params where itemCatId=?";
    sqlFn(sql, [cid], (result) => {
        if (result.length > 0) {
            res.send({
                status: 200,
                result,
            });
        } else {
            res.send({
                status: 500,
                msg: "暂无数据",
            });
        }
    });
});

/**
 * 上传图片 post请求 upload
 * 说明：
 *  1.后台安装 multer 模块   同时引入fs模块
 *  2.router.js入口文件导入模块
 *      const fs=require('fs')
        const multer=require('multer')
 *  3.上传图片 
 * 
 */

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./upload/");
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + "-" + file.originalname);
    },
});

const createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
};

const uploadFolder = "./upload/";
createFolder(uploadFolder);
const upload = multer({
    storage: storage,
});

router.post("/api/upload", upload.single("file"), function (req, res, next) {
    const file = req.file;
    res.json({
        res_code: "0",
        name: file.originalname,
        url: file.path,
    });
});

/**
 * 商品添加
 * 参数： title cid  category sellPoint price num descs paramsInfo image
 */
router.get("/backend/item/insertTbItem", (req, res) => {
    /**
     * 获取参数
     */
    let title = req.query.title || "";
    let cid = req.query.cid || "";
    let category = req.query.category || "";
    let sellPoint = req.query.sellPoint || "";
    let price = req.query.price || "";
    let num = req.query.num || "";
    let desc = req.query.descs || "";
    let paramsInfo = req.query.paramsInfo || "";
    let image = req.query.image || "";

    const sql = "insert into project values (null,?,?,?,?,?,?,?,?)";
    
    let arr = [cid, title, price, num, category, image, sellPoint, desc];

    sqlFn(sql, arr, (result) => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "添加成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "添加失败",
            });
        }
    });
});

/**
 * 商品删除接口 id
 */
router.get("/backend/item/deleteItemById", (req, res) => {
    let id = req.query.id;
    const sql = "delete from project where id=?";
    const arr = [id];
    sqlFn(sql, arr, (result) => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "删除成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "删除失败",
            });
        }
    });
});

/**
 * 批量删除 batchDelete  idArr Array  id标识
 * sql = "delete from A where id in (1,2,3)"
 */
router.get("/batchDelete", (req, res) => {
    let arr = req.query.idArr; //[] 数组格式 需要传递数据是 离散的数字格式
    // const sql =`delete from project where id in (?)`;
    let sql = "";
    function fun(arr) {
        //sql =`delete from project where id in (101,102,103)`;
        sql = `delete from project where id in (`;
        for (let i = 0; i < arr.length; i++) {
            sql += arr[i] + ","; //101,102,
        }
        sql = sql.slice(0, -1);
        sql = sql + ")";
        // console.log(sql);
    }
    fun(arr);
    sqlFn(sql, null, (result) => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "删除成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "删除失败",
            });
        }
    });
});

/**
 * 修改商品
 */

router.get("/backend/item/updateTbItem", (req, res) => {
    let id = req.query.id;
    let title = req.query.title || "";
    let sellPoint = req.query.sellPoint || "";
    let price = req.query.price || "";
    let cid = req.query.cid || "";
    let category = req.query.category || "";
    let num = req.query.num || "";
    let desc = req.query.descs || "";
    let paramsInfo = req.query.paramsInfo || "";
    let image = req.query.image || "";
    let sql =
        "update project set cid=?,title=?,price=?,num=?,category=?,image=?,sellPoint=?,desc=? where id=?";
    let arr = [cid, title, price, num, category, image, sellPoint, desc];
    sqlFn(sql, arr, (result) => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "修改成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "修改失败",
            });
        }
    });
});

/***
 * 登录接口
 */
router.post("/login", (req, res) => {
    const { username, password } = req.body; // 如果是not defined  一定要看清楚 变量字母或参数是否是对的 否则找半天都不知道哪里是错的
    // console.log(req.body);
    const sql = "select * from userinfo where username=? and password=?";
    const arr = [username, password]; /** 警告 */
    sqlFn(sql, arr, (result) => {
        if (result.length > 0) {
            let token = jwt.sign(
                {
                    username: result[0].username,
                    id: result[0].id,
                },
                config.jwtSecert,
                {
                    expiresIn: 20 * 1,
                }
            );
            res.send({
                status: 200,
                data: token,
            });
        } else {
            res.send({
                status: 404,
                data: "信息错误",
            });
        }
    });
});

/**
 * 注册接口
 */
router.post("/register", (req, res) => {
    const { username, password } = req.body; // 如果是not defined  一定要看清楚 变量字母或参数是否是对的 否则找半天都不知道哪里是错的
    // console.log(req.body);
    const sql = "insert into userinfo values(null,?,?)";
    const arr = [username, password]; /** 警告 */
    sqlFn(sql, arr, (result) => {
        if (result.affectedRows > 0) {
            res.send({
                msg: "注册成功",
                status: 200,
            });
        } else {
            res.status(401).json({
                error: "用户名或密码错误",
            });
        }
        // if (result.affectedRows !== 1) {
        //     res.send({
        //         msg: "注册用户失败，请稍后再试",
        //         status: 402,
        //     });
        // }
        // const sql2 = "select * from userinfo where username=?";
        // sqlFn(sql2, [ username ], (result) => {
        //     console.log(username);
        //     if (result.length > 0) {
        //         res.send({
        //             msg: "该账号已存在，请换个试试吧",
        //             status: 401,
        //         });
        //     }
        // });
    });
});

// router.post("/register", (req, res) => {
//     const { username, password } = req.body;
//     const sqlStr = `select * from userinfo where username = ?`;
//     const arr = [ username, password ];
//     sqlFn(sqlStr,arr[0],result => {
//         console.log(result,result.length);
//         if(result.length > 0) {
//             res.send({
//                 msg:'该账户已注册，请换个试试吧',
//                 status:401,
//             })
//         }
//     });
//     // 添加用户
//     const sql2 = `insert into userinfo values(null,?,?)`;
//     sqlFn(sql2,arr,result => {
//         if(result.affectedRows !== 1) {
//             res.send({
//                 msg:'注册用户失败',
//                 status:401,
//             })
//         }
//         res.send({
//             msg:"用户注册成功",
//             status:200
//         })
//     })
// });

router.get("/statistical", (req, res) => {
    res.send(
        Mock.mock({
            success: true,
            status: 200,
            "list|4": [
                {
                    "id|+1": 100,
                    "title|+1": ["总销售额", "访问量", "支付总量", "收藏量"],
                    "current|0-2000": 100,
                    "total|1000-999999": 200,
                },
            ],
        })
    );
});


/**
 * 规格参数列表  参数 page
 */
router.get("/backend/itemParam/selectItemParamAll", (req, res) => {
    const page = req.query.page || 1;
    const sqlLen = "select * from params where id";
    sqlFn(sqlLen, null, data => {
        let len = data.length;
        const sql = "select * from params order by id desc limit 8 offset " + (page - 1) * 8;
        sqlFn(sql, null, result => {
            if (result.length > 0) {
                res.send({
                    status: 200,
                    data: result,
                    pageSize: 8,
                    total: len
                })
            } else {
                res.send({
                    status: 500,
                    msg: "暂无数据"
                })
            }
        })
    })
})

/**
 * 规格参数  模糊查询  参数：search
 */
// router.get("/params/search", (req, res) => {
//     var search = req.query.search;
//     const sql = "select * from params where concat(`paramData`) like '%" + search + "%'";
//     sqlFn(sql, [search], result => {
//         if (result.length > 0) {
//             res.send({
//                 status: 200,
//                 result
//             })
//         } else {
//             res.send({
//                 status: 500,
//                 msg: '暂无数据'
//             })
//         }
//     })
// })

/**
 * 规格参数 添加 
 * 参数：itemCatId,content,specsName
 */
router.get("/backend/itemParam/insertItemParam", (req, res) => {
    var itemCatId = req.query.itemCatId;
    var paramsContent = req.query.content;
    var specsName = req.query.specsName;
    // console.log(itemCatId, paramsContent,specsName);
    var sql = "insert into params values (null,?,?,?)";
    sqlFn(sql, [itemCatId, paramsContent, specsName], result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "添加成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "添加失败"
            })
        }
    })
})


/**
 * 修改规格参数 cid content id  specsName
 */
// router.get("/update/category", (req, res) => {
//     var cid = req.query.cid;
//     var content = req.query.content;
//     var id = req.query.id;
//     var specsName = req.query.specsName;
//     var sql = "update params set paramData=? ,itemCatId=?,specsName=? where id=?";
//     sqlFn(sql, [content, cid, specsName, id], result => {
//         if (result.affectedRows > 0) {
//             res.send({
//                 status: 200,
//                 msg: "修改成功"
//             })
//         } else {
//             res.send({
//                 status: 500,
//                 msg: "修改失败"
//             })
//         }
//     })
// })

/**
 * 规格参数删除
 */
router.get("/params/delete", (req, res) => {
    var id = req.query.id;
    const sql = "delete from params where id=?"
    const arr = [id];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "删除成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "删除失败"
            })
        }
    })
})


/**
 * 规格参数类目结构数据获取 cid
 */
router.get("/category/data", (req, res) => {
    var cid = req.query.cid;
    var sql = "select * from params where itemCatId=?";
    sqlFn(sql, [cid], result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                result
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})



module.exports = router;
